import 'dart:async';
import 'dart:collection';
import 'dart:convert';
import 'dart:io';
import 'dart:math';

import 'package:flutter/services.dart';
import 'package:flutter_easy_permission/easy_permissions.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:get/get.dart';
import 'package:pocketfile/common/base/base_controller.dart';
import 'package:pocketfile/common/base/entity/res_error_entity.dart';
import 'package:pocketfile/common/utlis/permissions_utils.dart';
import 'package:pocketfile/module/home/entity/device_entity.dart';
import 'package:pocketfile/module/home/utils/method_channel_utils.dart';
import 'package:pocketfile/module/home/utils/socket_tcp_utils.dart';
import 'package:pocketfile/module/home/utils/utils.dart';
import 'package:vibration/vibration.dart';

class HomeController extends BaseController {
  final RxList<DeviceEntity> _bleDevicesList = RxList.empty();

  List<DeviceEntity> get bleDevicesList => _bleDevicesList.toList();

  final EasyRefreshController _refController = EasyRefreshController();

  EasyRefreshController get refController => _refController;
  ///权限处理
  final RxBool _checkPermission = RxBool(false);
  bool get checkPermission => _checkPermission.value;
  FlutterEasyPermission? _easyPermission;

  final Map<String, int> _deviceReceiveTimeMap = HashMap();
  final Map<String, int> _deviceIndexMap = HashMap();

  Timer? timer;
  String nowIP = "";

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    checkAppPermission();
    _initChannel();
    _startTimer();
  }

  @override
  void onClose() {
    // TODO: implement onClose
    timer?.cancel();
    _easyPermission?.dispose();
    super.onClose();
  }
  ///检查权限
  void checkAppPermission() async {
    const permissions = [
      Permissions.WRITE_EXTERNAL_STORAGE,
      Permissions.READ_EXTERNAL_STORAGE,
      Permissions.ACCESS_FINE_LOCATION,
      Permissions.ACCESS_COARSE_LOCATION,
      Permissions.CAMERA
    ];
    const permissionGroup = [PermissionGroup.DataNetwork];
    var b = await PermissionsUtils.checkPermission(permissions,permissionGroup);
    print('csd $b');
    if(b){
      //走正常展示逻辑
      print('权限已全部允许');
      _checkPermission.value = true;
    }
    _easyPermission = FlutterEasyPermission()..addPermissionCallback(
      onGranted: (requestCode, perms, perm) {
        if(perms?.length == permissions.length){
          //走正常展示逻辑
          print('申请的权限全部允许');
          _checkPermission.value = true;
        }
      },
      onDenied: (requestCode, perms, perm, isPermanent) {
        print("Android dddd onDenied:$perms");
        _checkPermission.value = false;
        //引导开启权限
      },
    );
  }

  // void updateHomeData() async {
  //   showLoading();
  //   Future.delayed(const Duration(milliseconds: 2000), () {
  //     hideLoading();
  //     _refController.finishRefresh();
  //   });
  // }

  ///添加设备(mock)
  void addBleDeviceMock() {
    List<DeviceEntity> dataList = [];
    for (var i = 0; i < 100; i++) {
      dataList.add(DeviceEntity(ip: "dddd" + i.toString()));
    }
    _bleDevicesList(dataList);
  }

  ///添加设备
  void addBleDevice(String data) {
    print(data);
    var deviceEntity = DeviceEntity.fromJson(jsonDecode(data));
    if (!deviceEntity.ip!.isNotEmpty) return;

    if (!_deviceReceiveTimeMap.containsKey(deviceEntity.ip)) {
      _bleDevicesList.add(deviceEntity);
      _deviceIndexMap[deviceEntity.ip!] = _bleDevicesList.length - 1;
    }
    _deviceReceiveTimeMap[deviceEntity.ip!] =
        DateTime
            .now()
            .millisecondsSinceEpoch;
  }

  ///移除设备
  void removeBleDevice() {
    _bleDevicesList.remove(0);
  }

  ///开启定时器
  void _startTimer() {
    timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      ///获取ip 与上次获得的对比，发生变化则重新开启
      if(_checkPermission.value)checkIP();
      ///超过5s没收到最新的设备则将其移除
      //dart中容器移除必须用removeWhere方法，否则会有并发问题
      _deviceReceiveTimeMap.removeWhere((key, value)  {
        bool b = DateTime.now().millisecondsSinceEpoch - value > 5000;
        if(b){
          _bleDevicesList.removeAt(_deviceIndexMap[key]!);
          _deviceIndexMap.remove(key);
        }
        return b;
      });
    });
  }

  ///原生通道
  void _initChannel() {
    MethodChannelUtils.getInstance().original2FlutterHandler((call) async {
      // 同样也是根据方法名分发不同的函数
      switch (call.method) {
        case "addDevice":
          {
            String msg = call.arguments.toString();
            addBleDevice(msg);
          }
          break;
      }
    });
  }

  void checkIP() async{
    var ip = await Utils.getIp();
    if(ip != nowIP){
      print('update IP: $ip ');
      if(nowIP.isNotEmpty)resErrorEntity.value = ResErrorEntity(1, "ip发生变化");
      nowIP = ip;
      MethodChannelUtils.getInstance().startBleBroadcast(ip);
      if(ip.isNotEmpty)SocketTcpUtils.getInstance().startListenTcpClient(ip,onReceiving,onDone);
    }
  }

  ///给另一端推送文件
  void pushFile(List<int> dataList,DeviceEntity _deviceEntity){
    SocketTcpUtils.getInstance().startTcpConnectServer(dataList,_deviceEntity.ip);
  }
  ///开始接收文件
  void onReceiving(){
    showLoading();
  }

  ///结束接收
  void onDone(){
    Vibration.vibrate(pattern: [100, 100, 100, 100, 100], amplitude: 255);
  hideLoading();
  }
}
